package com.maoyue.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson2.JSON;
import com.maoyue.demo.dao.UserDAO;
import com.maoyue.demo.entity.User;
import com.maoyue.demo.listener.DemoDataListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("YL")
@Slf4j
public class YangLinController {

    @Autowired
    UserDAO userDAO;

    static String path = "F:\\Excel-test\\test.xlsx";
    @GetMapping("read")
    public String ReadUser() {

        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取100条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(path, User.class, new PageReadListener<User>(dataList -> {
            for (User demoData : dataList) {
                log.info("读取到一条数据{}", JSON.toJSONString(demoData));
            }
        })).sheet().doRead();
        return "ok";
    }


    @GetMapping("write")
    public String WriteUser() {
        // 这里 需要指定写用哪个class去写
        try (ExcelWriter excelWriter = EasyExcel.write(path, User.class).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
            excelWriter.write(data(), writeSheet);
        }
        return "ok";
    }

    private List<User> data() {
        List<User> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            User data = new User();
            data.setPassword("123456" + i);
            data.setUserId(i);
            data.setUserName("yanglin" + i);
            list.add(data);
        }
        return list;
    }
}
